﻿/* Copyright (c) 2011, John Cronin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the copyright holder nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

/* The coercion mechanism
 * 
 * Following the variable assignment phase, we should have a code fragment (opcode_match)
 * and three variables, code_O1, code_O2, code_R, all of which are hloc_constraint.specific
 * 
 * The coercion mechanism takes the form:
 * 
 * code_O1 ---+                   +--> coerced_O1 ---+
 * (specific) |                   |    (any type)    |
 *            +--> pre_coercion --+                  +--> code fragment --> code_output_R --> post_coercion --> code_R
 *            |    (function)     |                  |                      (any type)        (function)        (specific)
 * code_O2 ---+                   +--> coerced_O2 ---+
 * (specific)                          (any type)
 * 
 * We thus define two functions, pre_coercion and post_coercion
 * 
 * coerced_O1, coerced_O2 and code_output_R are the expected inputs and outputs of the code fragment being tested,
 * although we have to modify code_output_R if it is expected to be the same as O1 or O2, but only after we have actually
 * defined O1 and O2 (i.e. we coerce the result after we do the inputs)
 * 
 * We define actual_O1, actual_O2 and actual_R to be the specific locations used by the code fragment
 * 
 * 
 * Thus pre_coercion takes as input code_O1, code_O2, coerced_O1, coerced_O2 and returns as output actual_O1, actual_O2,
 *  pre_ and post_coercion CodeBlocks and a cost
 *  
 * post_coercion takes as input code_R, code_output_R and returns as output actual_R, pre_ and post_coercion CodeBlocks
 *  and a cost
 */

using System;
using System.Collections.Generic;
using System.Text;

namespace tysila
{
    partial class Assembler
    {
        class Coercion
        {
            /* The class passed to pre_coercion */
            public class PreCoercion
            {
                public hloc_constraint code_O1, code_O2, coerced_O1, coerced_O2, actual_O1, actual_O2;
                public List<OutputBlock> pre_coercions = new List<OutputBlock>();
                public List<OutputBlock> post_coercions = new List<OutputBlock>();
                public int cost;
            }

            /* The class passed to post_coercion */
            public class PostCoercion
            {
                public hloc_constraint code_R, code_output_R, actual_R;
                public List<OutputBlock> pre_coercions = new List<OutputBlock>();
                public List<OutputBlock> post_coercions = new List<OutputBlock>();
                public int cost;
            }

            /* A complete coercion */
            public class MatchAndCoercion
            {
                public PreCoercion precoercion = new PreCoercion();
                public PostCoercion postcoercion = new PostCoercion();
                public Assembler.opcode_choice code_gen;
                public Assembler.IRegisterAllocator reg_alloc;
                public int cost { get { return precoercion.cost + postcoercion.cost; } }
            }

            /* The following functions decompose opcode matches that contain a list into a set of possible coercions */
            public static List<MatchAndCoercion> prepare_coercions(Assembler.opcode_choice match, Assembler.IRegisterAllocator reg_alloc)
            {
                List<MatchAndCoercion> ret = new List<MatchAndCoercion>();
                ret.AddRange(prepare_coercions(match, match.op1, match.op2, match.result, reg_alloc));
                return ret;
            }

            private static IEnumerable<MatchAndCoercion> prepare_coercions(Assembler.opcode_choice match, hloc_constraint O1, hloc_constraint O2, hloc_constraint R, Assembler.IRegisterAllocator reg_alloc)
            {
                List<MatchAndCoercion> ret = new List<MatchAndCoercion>();

                if (O1.constraint == hloc_constraint.c_.List)
                {
                    foreach (hloc_constraint c in O1.specific_list)
                        ret.AddRange(prepare_coercions(match, c, O2, R, reg_alloc));
                }
                else
                {
                    if (O2.constraint == hloc_constraint.c_.List)
                    {
                        foreach (hloc_constraint c in O2.specific_list)
                            ret.AddRange(prepare_coercions(match, O1, c, R, reg_alloc));
                    }
                    else
                    {
                        if (R.constraint == hloc_constraint.c_.List)
                        {
                            foreach (hloc_constraint c in R.specific_list)
                                ret.AddRange(prepare_coercions(match, O1, O2, c, reg_alloc));
                        }
                        else
                        {
                            MatchAndCoercion mac = new MatchAndCoercion();
                            mac.code_gen = match;
                            mac.reg_alloc = reg_alloc.Clone();
                            mac.precoercion.coerced_O1 = O1;
                            mac.precoercion.coerced_O2 = O2;
                            mac.postcoercion.code_output_R = R;
                            ret.Add(mac);
                        }
                    }
                }

                return ret;
            }

            // This function returns the best possible coercion
            public static MatchAndCoercion get_best_coercion(Assembler ass, Assembler.IRegisterAllocator reg_alloc, Assembler.opcode_choice code_gen, hloc_constraint code_O1, hloc_constraint code_O2, hloc_constraint code_R)
            {
                List<MatchAndCoercion> coercions = prepare_coercions(code_gen, reg_alloc);

                MatchAndCoercion best = null;
                int best_cost = int.MaxValue;

                foreach (MatchAndCoercion mac in coercions)
                {
                    mac.precoercion.code_O1 = code_O1;
                    mac.precoercion.code_O2 = code_O2;
                    mac.postcoercion.code_R = code_R;

                    if (pre_coercion(ass, reg_alloc, mac.precoercion) && post_coercion(ass, reg_alloc, mac.postcoercion))
                    {
                        if (mac.cost < best_cost)
                        {
                            best = mac;
                            best_cost = mac.cost;
                        }
                    }
                }

                return best;
            }

            public static bool pre_coercion(Assembler ass, Assembler.IRegisterAllocator reg_alloc, PreCoercion c)
            {
                // We use a working value for code_O1 and code_O2 as me may change them in the course of the coercion (e.g. if we swap them)

                hloc_constraint working_code_O1 = c.code_O1;
                hloc_constraint working_code_O2 = c.code_O2;

                // Decide if we need to swap O1 and O2
                if ((hloc_constraint.SpecificCompare(working_code_O1, c.coerced_O2)) || (hloc_constraint.SpecificCompare(working_code_O2, c.coerced_O1)))
                {
                    // Swap O1 with O2
                    try
                    {
                        c.pre_coercions.Add(new CodeBlock { Code = ass.SwapLocation(working_code_O1.specific, working_code_O2.specific) });
                        c.post_coercions.Insert(0, new CodeBlock { Code = ass.SwapLocation(working_code_O1.specific, working_code_O2.specific) });
                    }
                    catch (Exception)
                    {
                        return false;
                    }

                    hloc_constraint tmp = working_code_O1;
                    working_code_O1 = working_code_O2;
                    working_code_O2 = tmp;
                }

                if (hloc_constraint.IsAssignableTo(c.coerced_O1, working_code_O1))
                    c.actual_O1 = working_code_O1;
                else
                {
                    hloc_constraint? act_dest = try_coercion(ass, reg_alloc, c, c.coerced_O1, working_code_O1);
                    if (act_dest == null)
                        return false;
                    c.actual_O1 = act_dest.Value;
                }
                if (hloc_constraint.IsAssignableTo(c.coerced_O2, working_code_O2))
                    c.actual_O2 = working_code_O2;
                else
                {
                    hloc_constraint? act_dest = try_coercion(ass, reg_alloc, c, c.coerced_O2, working_code_O2);
                    if (act_dest == null)
                        return false;
                    c.actual_O2 = act_dest.Value;
                }

                return true;
            }

            private static hloc_constraint? try_coercion(Assembler ass, Assembler.IRegisterAllocator reg_alloc, PreCoercion c, hloc_constraint dest, hloc_constraint src)
            {
                // Try and coerce src to dest

                // If dest is any_of_type, we need to try and assign one
                hloc_constraint act_dest = dest;
                if (dest.constraint == hloc_constraint.c_.AnyOfType)
                {
                    act_dest = new hloc_constraint { constraint = hloc_constraint.c_.Specific, specific = reg_alloc.GetRegister(dest, var.Coerce()) };
                }

                if (!src.IsSpecificOrConst)
                    throw new Exception("src is not specific or immediate: " + src.ToString());
                if (!act_dest.IsSpecificOrConst)
                    throw new Exception("dest is not specific or immediate: " + dest.ToString());

                if (ass.CanCoerce(act_dest.specific, src.specific, c.pre_coercions, reg_alloc))
                    return act_dest;
                else
                    return null;
            }

            public static bool post_coercion(Assembler ass, Assembler.IRegisterAllocator reg_alloc, PostCoercion c)
            {
                return true;
            }
        }
    }
}
